<?php 
namespace Pig\Controller;
use Pig\Model;
class BeusersController extends BaseController {
    /*
     * 后台用户列表
     */
    public function index() {
        //实例化后台用户
        $BeUser = D('BeUsers');
        $BeGroup = D('BeGroups');

        //处理ajax请求
        if (IS_AJAX) {
            //(标记)20160118 权限修复
            //检验权限
            $access_user_edit = checkAccess(CONTROLLER_NAME, 'user_edit');
            $access_user_del = checkAccess(CONTROLLER_NAME, 'user_del');
            $access_group_edit = checkAccess(CONTROLLER_NAME, 'group_edit');
            $access_group_del = checkAccess(CONTROLLER_NAME, 'group_del');
            switch (I('request.cmd')) {
                //加载列表
                case 'user_list':
                    //条件处理
                    $where = "deleted=0";
                    //(标记)20160118 权限修复
                    //检查用户权限
                    $User = session('BEUSER');
                    if($User['usergroup']!=1)$where .= " and id={$User['id']}";
                    $sortingArray = array('id', '', 'usergroup', '', '', '', 'hidden', '');
                    $ascDesc = I('post.sSortDir_0');
                    $sortColumn = $sortingArray[I('post.iSortCol_0')];
                    if (I('post.sSearch')) {
                        $sSearch = mysql_real_escape_string(I('post.sSearch'));
                        $where .= " and (username like '%{$sSearch}%' or email like '%{$sSearch}%')";
                    }

                    //main res
                    $dataArray = array();
                    $total = $BeUser->where($where)->count();
                    $list = $BeUser->where($where)->order($sortColumn . ' ' . $ascDesc)->limit(I('post.iDisplayStart') . ',' . I('post.iDisplayLength'))->select();
                    if ($list) {
                        foreach ($list as $row) {
                            //(标记)20160118 权限修复
                            $edit = $access_user_edit ? '<a href="' . U('Beusers/user_edit', array('id' => $row['id'])) . '" class="btn green-stripe mini">编辑</a>' : "";
                            $del = $access_user_del ? '<a href="' . U('Beusers/del', array('id' => $row['id'], 'type' => 'users')) . '" class="btn red-stripe mini del">删除</a></div>' : "";
                            $dataArray[] = array(
                                $row['id'],
                                $row['username'],
                                $row['name'],
                                M('BeGroups')->where(array('id' => $row['usergroup']))->getField('title'),
                                $row['lastloginip'] ? $row['lastloginip'] : '-',
                                $row['lastlogin'] ? date('Y-m-d H:i:s', $row['lastlogin']) : '-',
                                //$row['email'],
                                $row['hidden'] ? '<span class="label label-inverse">停用</span>' : '<span class="label label-success">启用</span>',
                                //(标记)20160118 权限修复
                                '<div class="action_btn">'.$edit.$del.'</div>'
                            );
                        }
                    }

                    //json数据
                    $outputArray = array(
                        'sEcho' => I('post.sEcho'),
                        'iTotalRecords' => $total,
                        'iTotalDisplayRecords' => $total,
                        'aaData' => $dataArray
                    );
                    echo json_encode($outputArray);
                    break;
                //加载组列表
                case 'group_list':
                    //条件处理
                    $where = "deleted=0";
                    $sortingArray = array('id', 'title', '', 'hidden', '');
                    $ascDesc = I('post.sSortDir_0');
                    $sortColumn = $sortingArray[I('post.iSortCol_0')];
                    if (I('post.sSearch')) {
                        $sSearch = mysql_real_escape_string(I('post.sSearch'));
                        $where .= " and (title like '%{$sSearch}%' or remark like '%{$sSearch}%')";
                    }

                    //main res
                    $dataArray = array();
                    $total = $BeGroup->where($where)->count();
                    $list = $BeGroup->where($where)->order($sortColumn . ' ' . $ascDesc)->limit(I('post.iDisplayStart') . ',' . I('post.iDisplayLength'))->select();
                    if ($list) {
                        foreach ($list as $row) {
                            //(标记)20160118 权限修复
                            $edit = $access_group_edit ? '<a href="' . U('Beusers/group_edit', array('id' => $row['id'])) . '" class="btn green-stripe mini">编辑</a>' : "";
                            $del = $access_group_del ? '<a href="' . U('Beusers/del', array('id' => $row['id'], 'type' => 'groups')) . '" class="btn red-stripe mini del">删除</a>' : "";
                            $dataArray[] = array(
                                $row['id'],
                                $row['title'],
                                $row['remark'],
                                $row['hidden'] ? '<span class="label label-inverse">停用</span>' : '<span class="label label-success">启用</span>',
                                //(标记)20160118 权限修复
                                '<div class="action_btn">'.$edit.$del.'</div>'
                            );
                        }
                    }

                    //json数据
                    $outputArray = array(
                        'sEcho' => I('post.sEcho'),
                        'iTotalRecords' => $total,
                        'iTotalDisplayRecords' => $total,
                        'aaData' => $dataArray
                    );
                    echo json_encode($outputArray);
                    break;
                default:
                    break;
            }
            exit;
        }

        $this->display();
    }

    /**
     * 添加后台用户
     */
    public function user_save() {
        $id = I('get.id') ? I('get.id') : null;
        //(标记)20160118 权限修复
        //检查用户权限
        $User = session('BEUSER');
        if($User['usergroup']!=1 && $id!=$User['id']){
            $this->error("无操作权限！");
        }
        $usergroup = M('BeGroups')->where(array('deleted' => 0,'id' => array('gt',1)))->Field('id as "0",title as "1"')->select();
        //debug(M()->_sql());
        $tca = array(
            'username' => array(
                'label' => '用户名',
                'type' => 'text',
                'required' => true,
            ),
            'password' => array(
                'label' => '密码',
                'type' => 'password',
                'help' => '编辑时不输入表示不修改密码'
            ),
            'name' => array(
                'label' => '名称',
                'type' =>'text',
                'required' => true
            ),
            'usergroup' => array(
                'label' => '用户组',
                'type' =>'select',
                'data' => $usergroup,
                'required' => true,
            )
        );
        if (IS_POST) {
            foreach ($_POST as $key => $value) {
                if(@$tca[$key]['required'] && !preg_match('/\S/', $value)){
                    $this->error($tca[$key]['label'] . '*是必填项!');
                }
            }
            //(标记)20160118 权限修复
            /*if($User['usergroup']!=1){
                unset($_POST['usergroup']);
            }*/
            $BeUsers = D('BeUsers');
            $result = $BeUsers->create();//'', $id ? \Think\Model::MODEL_UPDATE : \Think\Model::MODEL_INSERT
            if (!$result) {
                $this->error($BeUsers->getError());
            } else {
                if ($BeUsers->password) {
                    $BeUsers->password = parent::encryption_backend($BeUsers->password);
                } else {
                    unset($BeUsers->password);
                }

                if ($id) {
                    $BeUsers->tstamp = time();
                    $BeUsers->where(array('id' => $id))->save();
                    $message = '编辑成功!';
                } else {
                    $BeUsers->crdate = time();
                    $BeUsers->tstamp = time();
                    $BeUsers->add();
                    $message = '添加成功!';
                }
                $this->success($message, U(CONTROLLER_NAME.'/index'));
                exit;
            }
        }
        $info = D('BeUsers')->where(array('id' => $id))->find();
        $info['password'] = '';
        $this->assign('groupList', M('BeGroups')->where(array('deleted' => 0))->select());
        $this->assign('info', D('BeUsers')->where(array('id' => $id))->find());
        parent::autoFields($tca,$info);
        $this->display('info');
    }
    /**
     * 编辑后台用户
     */
    //(标记)20160118 权限修复
    public function user_edit() {
        $this->user_save();
    }

    /**
     * 添加后台用户组
     */
    public function group_save() {
        import("@.Util.Tree");
        $id = I('get.id') ? I('get.id') : null;
        $Access = M('Access');

        if (IS_POST) {
            $BeGroups = D('BeGroups');
            $result = $BeGroups->create();
            if (!$result) {
                $this->error($BeGroups->getError());
            } else {
                if (!isset($_POST['hidden'])) {
                    $BeGroups->hidden = 1;
                }
                if ($id) {
                    $BeGroups->tstamp = time();
                    $BeGroups->where(array('id' => $id))->save();
                    $message = '编辑成功!';
                } else {
                    $BeGroups->crdate = time();
                    $BeGroups->tstamp = time();
                    $id = $BeGroups->add();
                    $message = '添加成功!';
                }
                //处理权限分配
                if (I('post.access')) {
                    $Access->where(array('group_id' => I('get.id')))->delete(); //删除目录权限配置，等待进行新权限分配
                    foreach (I('post.access') as $menu_id) {
                        $Access->add(array(
                            'group_id' => $id,
                            'menu_id' => $menu_id
                        ));
                    }
                }else{
                    $this->error('权限不能为空');
                }

                $this->success($message, U('Beusers/index'));
                exit;
            }
        }

        $accessRows = $Access->where(array('group_id' => I('get.id')))->select();
        $ids=array();
        //Role tree
        $accessArray = array();
        if ($accessRows) {
            foreach ($accessRows as $row) {
                $accessArray[] = $row['menu_id'];
            }
        }
        $array = M('Menu')->where("deleted=0 and app='Admin'")->select();//id>1 and 
        foreach ($array as $key => $val) {
            $array[$key]['checked'] = in_array($val['id'], $accessArray) ? 'checked="checked"' : '';
        }
        //js选择
        foreach($array as $v){
            $ids['role'][$v['id']]=$v['parent_id'];
        }
        $this->assign('ids',json_encode($ids));
        $tree = new \Tree();
        $tree->init($array);
        $this->assign('role_tree', $tree->get_tree(0, "<li>\$spacer <input type='checkbox' id='role_\$id' name='access[]' value='\$id' \$checked /><label for='role_\$id'>\$title</label></li>"));

        $this->assign('info', D('BeGroups')->where(array('id' => I('get.id')))->find());
        $this->display('group_info');
    }
    //(标记)20160118 权限修复
    /**
     * 编辑后台用户组
     */
    public function group_edit() {
        $this->group_save();
    }

    /**
     * 删除后台用户组
     */
    public function group_del() {
        D('BeGroups')->where(array('id' => I('get.id')))->save(array(
            'deleted' => 1
        ));
        $this->success('删除成功!', U('Beusers/index'));
        exit;
    }
}

?>